package com.demo.blog;

import com.demo.common.model.Blog;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.template.activerecord.PageSqlKit;
import com.jfinal.template.activerecord.SqlPara;
import com.jfinal.template.activerecord.SqlUtil;
import com.jfinal.template.kit.Kv;

/**
 * BlogController
 * 所有 sql 与业务逻辑写在 Model 或 Service 中，不要写在 Controller 中，养成好习惯，有利于大型项目的开发与维护
 */
@Before(BlogInterceptor.class)
public class BlogController extends Controller {
    public void index() {
        setAttr("blogPage", Blog.me.paginate(getParaToInt(0, 1), 10));
        render("blog.html");
    }

    public void add() {
    }

    @Before(BlogValidator.class)
    public void save() {
        getModel(Blog.class).save();
        redirect("/blog");
    }

    public void edit() {
        setAttr("blog", Blog.me.findById(getParaToInt()));
    }

    @Before(BlogValidator.class)
    public void update() {
        getModel(Blog.class).update();
        redirect("/blog");
    }

    public void delete() {
        Blog.me.deleteById(getParaToInt());
        redirect("/blog");
    }

    public void queryList() {
        String ids = this.getPara("ids");
        String title = this.getPara("title");
        String content = this.getPara("content");

        Kv kv = new Kv();
        kv.set("ids", ids);
        kv.set("title", title);
        kv.set("content", content);

        SqlPara sqlPara = SqlUtil.getSqlPara("blog.queryList", kv);
        String[] sql = PageSqlKit.parsePageSql(sqlPara.getSql());

        Page<Record> page = Db.paginate(1, 10, sql[0], sql[1], sqlPara.getPara());
        setAttr("page", page);
        renderJson();
    }
}


